<?php
/**
 * 
 * @authors Liujinbi (857053791@QQ.com)
 * @date    2017-11-23 16:21:42
 * @version $Id$
 */
namespace app\admin\controller;
use think\Db;
use think\Request;
use think\Log;
use think\Config;


class Firstorder extends Base {
    
    function index(){
        $iw=Request()->param();

    	$start_time=isset($iw['start_time'])?strtotime($iw['start_time']):'';
    	$end_time=isset($iw['end_time'])?strtotime($iw['end_time']):'';

    	if($end_time){
            $_end_time=getOneDay($end_time);
            // $_end_time=$_end_time['et'];
            if ($end_time==$_end_time['st']) {
                $end_time=$_end_time['et'];
            }
        }else{
            $end_time=getOneDay();
            $end_time=$end_time['et'];
        }

        if ($start_time) {
            // $start_time=getOneDay($start_time);
            // $start_time=$start_time['st'];
        }else{
            $start_time=getDayRegion($end_time,1);
            $start_time=$start_time['st'];
        }
        
        $iw['start_time']=date('Y-m-d H:i:s',$start_time);
        $iw['end_time']=date('Y-m-d H:i:s',$end_time);
        if ($iw['selt']!=='0') {
            $iw['selt']=$iw['selt']?:1;
        }
    	$data['w']=$iw;

    	$orders = Db::field('o.order_money,e.name as agent_name,o.user_id,o.receiver_mobile,o.receiver_name,o.pay_time,u.register_time,s.shop_name,o.order_id')
    	->table('sdzx_order')->alias('o')
    	->join('sdzx_user u','o.user_id=u.id')
    	->join('sdzx_shop s','o.user_id=s.user_id','left')
    	->join('sdzx_employee e','s.agent_id=e.id','left')
    	->where("pay_status=1 and pay_time between '{$iw['start_time']}' and '{$iw['end_time']}'")
    	->group('user_id')
    	->order('pay_time asc')
    	// ->having('count(order_id)=1')
    	->select();
    		
    	$user_idsarr = array_column($orders,'user_id');
 		$user_idstring = implode(',', $user_idsarr)?:'0';
    	$_user = Db::field('user_id')->name('order')->group('user_id')->where("pay_status=1 and pay_time < '{$iw['start_time']}' and user_id in({$user_idstring})")->column('user_id');

    	$newarr = array_diff($user_idsarr, $_user);
    	$return_arr = [];
    	foreach ($orders as $k => $v) {
    		if (in_array($v['user_id'], $newarr)) {
    			$return_arr[] = $v;
                $data['totalmoney'] += $v['order_money'];
    		}
    	}
    	$data['list']=$return_arr;
    	return $this->fetch('',$data);
    }
}